#include <benchmark/benchmark.h>
#include <vector>
#include <random>

constexpr std::size_t kSize = 1 << 20;  // 1M 元素
constexpr int kIterations = 8;

void init_data(std::vector<int>& a, std::vector<int>& b) {
    std::mt19937 rng(42);
    std::uniform_int_distribution<int> dist(1, 100);
    for (std::size_t i = 0; i < kSize; ++i) {
        a[i] = dist(rng);
        b[i] = dist(rng);
    }
}

// 与截图一致：编译器必须假设 a 和 b 可能别名
void func_alias(int* a, int* b, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] += *b;
    }
}

// 使用 restrict 告知编译器 a 与 b 不会指向重叠内存
void func_restrict(int* __restrict a, int* __restrict b, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] += *b;
    }
}

static void BM_FuncAlias(benchmark::State& state) {
    std::vector<int> a(kSize);
    std::vector<int> b(kSize);
    init_data(a, b);
    for (auto _ : state) {
        func_alias(a.data(), b.data(), static_cast<int>(a.size()));
        benchmark::DoNotOptimize(a);
        benchmark::ClobberMemory();
    }
}
BENCHMARK(BM_FuncAlias);

static void BM_FuncRestrict(benchmark::State& state) {
    std::vector<int> a(kSize);
    std::vector<int> b(kSize);
    init_data(a, b);
    for (auto _ : state) {
        func_restrict(a.data(), b.data(), static_cast<int>(a.size()));
        benchmark::DoNotOptimize(a);
        benchmark::ClobberMemory();
    }
}
BENCHMARK(BM_FuncRestrict);

BENCHMARK_MAIN();